package com.hbx.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hbx.eduservice.entity.EduSubject;
import com.hbx.eduservice.entity.excel.SubjectData;
import com.hbx.eduservice.entity.subject.OneSubject;
import com.hbx.eduservice.entity.subject.TwoSubject;
import com.hbx.eduservice.listener.SubjectExcelListener;
import com.hbx.eduservice.mapper.EduSubjectMapper;
import com.hbx.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author hbx
 * @since 2023-10-01
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Override
    public void saveSubject(MultipartFile file,EduSubjectService eduSubjectService) {
        try {
            InputStream stream = file.getInputStream();
            //调用方法读取
            EasyExcel.read(stream, SubjectData.class,new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<OneSubject> getAllOneTwoSubject() {
        //查询一级分类
        LambdaQueryWrapper<EduSubject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduSubject::getParentId,"0");
        List<EduSubject> oneSubjectList = this.list(queryWrapper);

        //查询二级分类
        LambdaQueryWrapper<EduSubject> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.ne(EduSubject::getParentId,"0");
        List<EduSubject> twoSubjectList = this.list(queryWrapper1);

        //封装list集合
        List<OneSubject> finalSubjectList = new ArrayList<>();
        for (EduSubject eduSubject : oneSubjectList) {
            OneSubject oneSubject = new OneSubject();
            oneSubject.setId(eduSubject.getId());
            oneSubject.setTitle(eduSubject.getTitle());
            finalSubjectList.add(oneSubject);
        }

        for (int i = 0; i < finalSubjectList.size(); i++) {
            for (int j = 0; j < twoSubjectList.size(); j++) {
                if(finalSubjectList.get(i).getId().equals(twoSubjectList.get(j).getParentId())){
                    List<TwoSubject> children = finalSubjectList.get(i).getChildren();
                    TwoSubject twoSubject = new TwoSubject();
                    EduSubject eduSubject = twoSubjectList.get(j);
                    BeanUtils.copyProperties(eduSubject,twoSubject);
                    children.add(twoSubject);
                }
            }
        }

        return finalSubjectList;
    }
}
